<?php
namespace app\admin\controller;

use app\admin\controller\Common;
use think\Db;
use PHPExcel_IOFactory;
use think\facade\Env;
use PHPQRCode\QRcode;

class Speed extends Common
{
    public $think;

    public function __construct()
    {
        parent::__construct();
        $this->think = $_SESSION['think'];
    }
    /*
       *项目管理
      */
    function activityList()
    {
        $title = '项目管理';
        $inputData = input('get.');
        $res = $list = array();
        $p = empty($_GET['p']) ? 1 : $_GET['p'];
        $size = empty($_REQUEST['size']) ? 25 : $_REQUEST['size'];
        $where = 'id > 0';
        if ($this->think['admin_id'] > 1) {
            $where = 'admin_id = ' . $this->think['admin_id'];
        }
        if ($inputData['keyword']) {
            $where .= " and name like '%" . $inputData['keyword'] . "%'";
            $this->assign('keyword', $inputData['keyword']);
        }
        $count = Db::name('speed_activity')->where($where)->count();// 查询满足要求的总记录数
        $res = Db::name('speed_activity')->where($where)->order('id desc')->paginate($size, $count,
            ['query' => request()->param()])->each(function ($item, $key) {
            $item['created_at'] = date('Y-m-d H:i:s',$item['created_at']);
            $item['updated_at'] = date('Y-m-d H:i:s',$item['updated_at']);
            return $item;
        });
        $page = $res->render();
        $this->assign('title', $title);
        $this->assign('list', $res);// 赋值数据集
        $this->assign('page', $page);// 赋值分页输出
        $this->assign('total', $count);// 数据总数

        return view('activityList');
    }
    public function activity()
    {
        $act = input('route.act') ? input('route.act') : 'add';
        $info = array();
        if (input('route.id')) {
            $id = input('route.id');
            $info = db('speed_activity')->where('id=' . $id)->find();
            $date = $info['updated_at'];
            $info['created_at'] = date('Y-m-d H:i:s',  $info['created_at']);

        } else {
            $date = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
        }
        $this->assign('act', $act);
        $this->assign('info', $info);
        $this->assign('date', $date);// 赋值数据集
        return view();
    }
    public function activityHandle()
    {
        $data = input('post.');
        $act = $data['act'];
        $data['updated_at'] = time();
        $data['admin_id'] = $this->think['admin_id'];
        unset($data['act']);
        if ($data['status'] == 1){
            $r = db('speed_activity')->where('status=1')->update(array('status'=>0));
        }
        if ($act == 'add') {
            $data['created_at'] = time();
            $r = db('speed_activity')->insertGetId($data);
            if ($r) {
                $json['status'] = 1;
                $json['message'] = lang('success');
                /*********************记录日志***********************/
                addLog(session('speed_pro') . '添加活动成功-' . $data['name'] . ' [ ID:' . $r . ' ]');
                echo json_encode($json);
                exit;
            } else {
                $json['status'] = 0;
                $json['message'] =lang('fail');
                echo json_encode($json);
                exit;
            }
        }

        if ($act == 'edit') {
            $id = $data['id'];
            unset($data['id']);
            try {
                $r = db('speed_activity')->where('id=' . $id)->update($data);
            } catch (ValidateException $e) {
                // 这是进行验证异常捕获
                return json($e->getError());
            } catch (\Exception $e) {
                // 这是进行异常捕获
                return json($e->getMessage());
            }
            // dump($article_id);exit;
            if ($r !== false) {
                $json['status'] = 1;
                $json['message'] = lang('success');
                /*********************记录日志***********************/
                addLog(session('speed_activity') . '添加活动成功-' . $data['name'] . ' [ ID:' . $r . ' ]');
                echo json_encode($json);
                exit;
            } else {
                $json['status'] = 0;
                $json['message'] = lang('fail');
                echo json_encode($json);
                exit;
            }

        }

    }
    /*
    *项目管理
   */
    function proList()
    {
        $title = '项目管理';
        $inputData = input('get.');
        $res = $list = array();
        $p = empty($_GET['p']) ? 1 : $_GET['p'];
        $size = empty($_REQUEST['size']) ? 25 : $_REQUEST['size'];
        $where = 'id > 0';
        if ($this->think['admin_id'] > 1) {
            $where = 'admin_id = ' . $this->think['admin_id'];
        }
        if ($inputData['keyword']) {
            $where .= " and name like '%" . $inputData['keyword'] . "%'";
            $this->assign('keyword', $inputData['keyword']);
        }
        $count = Db::name('speed_pro')->where($where)->count();// 查询满足要求的总记录数
        $res = Db::name('speed_pro')->where($where)->order('id desc')->paginate($size, $count,
            ['query' => request()->param()])->each(function ($item, $key) {
            $item['created_at'] = date('Y-m-d H:i:s',$item['created_at']);
            $item['updated_at'] = date('Y-m-d H:i:s',$item['updated_at']);
            return $item;
        });
        $temp = db('speed_activity')->where($where)->select();
        $activity=[];
        foreach ($temp as $value) {
            $activity[$value['id']] = $value['name'];
        }
        $page = $res->render();
        $this->assign('activity', $activity);
        $this->assign('title', $title);
        $this->assign('list', $res);// 赋值数据集
        $this->assign('page', $page);// 赋值分页输出
        $this->assign('total', $count);// 数据总数

        return view('proList');
    }
    public function pro()
    {
        $act = input('route.act') ? input('route.act') : 'add';
        $info = array();
        if (input('route.id')) {
            $id = input('route.id');
            $info = db('speed_pro')->where('id=' . $id)->find();
            $date = $info['updated_at'];
            $info['created_at'] = date('Y-m-d H:i:s',  $info['created_at']);

        } else {
            $date = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
        }
        $where = 'id > 0';
        if ($this->think['admin_id'] > 1) {
            $where = 'admin_id = ' . $this->think['admin_id'];
        }
        $activityList = db('speed_activity')->where($where)->select();
        $this->assign('activityList', $activityList);
        $this->assign('act', $act);
        $this->assign('info', $info);
        $this->assign('date', $date);// 赋值数据集
        return view();
    }
    public function proHandle()
    {
        $data = input('post.');
        $act = $data['act'];
        $data['updated_at'] = time();
        $data['admin_id'] = $this->think['admin_id'];
        unset($data['act']);
        if ($act == 'add') {
            $data['created_at'] = time();
            $r = db('speed_pro')->insertGetId($data);
            $data['id'] = $r;
            $res = $this->importExcel($data);
            if (!$res) {
                $data = array('errcode' => 1, 'message' => lang('excel_empty'));
            }
            if ($r) {
                $json['status'] = 1;
                $json['message'] = lang('success');
                /*********************记录日志***********************/
                addLog(session('speed_pro') . '添加活动成功-' . $data['name'] . ' [ ID:' . $r . ' ]');
                echo json_encode($json);
                exit;
            } else {
                $json['status'] = 0;
                $json['message'] =lang('fail');
                echo json_encode($json);
                exit;
            }
        }

        if ($act == 'edit') {
            $id = $data['id'];
            $res = $this->importExcel($data);
            if (!$res) {
                $data = array('errcode' => 1, 'message' => lang('excel_empty'));
            }
            unset($data['id']);
            try {
                $r = db('speed_pro')->where('id=' . $id)->update($data);
            } catch (ValidateException $e) {
                // 这是进行验证异常捕获
                return json($e->getError());
            } catch (\Exception $e) {
                // 这是进行异常捕获
                return json($e->getMessage());
            }
            // dump($article_id);exit;
            if ($r !== false) {
                $json['status'] = 1;
                $json['message'] = lang('success');
                /*********************记录日志***********************/
                addLog(session('speed_pro') . '添加活动成功-' . $data['name'] . ' [ ID:' . $r . ' ]');
                echo json_encode($json);
                exit;
            } else {
                $json['status'] = 0;
                $json['message'] = lang('fail');
                echo json_encode($json);
                exit;
            }

        }

    }
    /**
     * 获取导入模板
     * @return string $file 模板excel的相对路径
     */
    public function getUserTemplate()
    {
        $act = input('get.act');
        $file = '';
        if ($act == 'excel') {
            $file = $_SERVER['HTTP_ORIGIN']. DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'template' . DIRECTORY_SEPARATOR . 'user_list.xlsx';
        }
        $json['status'] = 1;
        $json['message'] = lang('success');
        $json['file'] = $file;
        echo json_encode($json);
        return;
    }
    //导入表格
    public function importExcel($arr)
    {
        //获取上传到后台的文件名
        $fileName = $arr['excel'];
        //获取文件路径
        $filePath = Env::get('root_path') . $fileName;
        //获取文件后缀
        $suffix = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        $xlsx = ['xlsx', 'xlsm', 'xltx', 'xltm'];
        $xls = ['xls', 'xlt'];
        $res = 0;
        //判断哪种类型
        if (in_array($suffix, $xlsx)) {
            $reader = \PHPExcel_IOFactory::createReader('Excel2007');
            $res = 1;
        }
        if (in_array($suffix, $xls)) {
            $reader = \PHPExcel_IOFactory::createReader('Excel5');
            $res = 1;
        }
        if ($res == 0) {
            return false;
        }

        //载入excel文件
        $excel = $reader->load("$filePath", $encode = 'utf-8');
        //读取第一张表
        $sheet = $excel->getSheet(0);
        //获取总行数
        $row_num = $sheet->getHighestRow();
        //获取总列数
        $col_num = $sheet->getHighestColumn();

        $data = []; //数组形式获取表格数据
        for ($i = 2; $i <= $row_num; $i++) {
            $data[$i]['name'] = $sheet->getCell("A" . $i)->getValue();
            $data[$i]['sex'] = $sheet->getCell("B" . $i)->getValue();
            $data[$i]['code'] = $sheet->getCell("C" . $i)->getValue();
            $data[$i]['pro_id'] = $arr['id'];
            $data[$i]['admin_id'] = $arr['admin_id'];
        }
        db('speed_users')->where('pro_id='.$arr['id'])->delete();
        $result   =  db('speed_users')->insertAll($data);
        return $result;
    }

}


?>
